package com.ruoyi.framework.wechat;

import com.alibaba.fastjson.JSON;
import com.ruoyi.by.health.component.WechatAuthenticationToken;
import com.ruoyi.framework.web.service.UserDetailsServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.HashSet;

/**
 * @ClassName WechatAuthenticationProvider
 * @Author 张敬琦
 * @Description 添加描述
 * @Date 2024/1/11 20:51
 **/
@Slf4j
public class WechatAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) {

        WechatAuthenticationToken authenticationToken = (WechatAuthenticationToken) authentication;
        String code = (String) authenticationToken.getPrincipal();

        UserDetails userDetails = ((UserDetailsServiceImpl) userDetailsService).loadEmpByEmpCode(code);
        log.info("-----------userDetails:{}", JSON.toJSONString(userDetails));
        WechatAuthenticationToken result = new WechatAuthenticationToken(userDetails, new HashSet<>());
        result.setDetails(authentication.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return WechatAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    protected UserDetailsService getUserDetailsService() {
        return this.userDetailsService;
    }
}
